<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>全选练习</title>
		<script type="text/javascript">
			window.onload = function(){
				//1.#checkedAllBtn
				document.getElementById("checkedAllBtn").onclick = function(){
					var items = document.getElementsByName("items");
					for(var i=0;i<items.length;i++){
						// 通过多选框的checked属性可以来获取或设置多选框的选中状态
						items[i].checked = true;
					}
					// 全选按钮也要同步选中
					document.getElementById("checkedAllBox").checked = true;
				}
				
				//2.#checkedNoBtn
				document.getElementById("checkedNoBtn").onclick = function(){
					var items = document.getElementsByName("items");
					for(var i=0;i<items.length;i++){
						items[i].checked = false;
					}
					// 全选按钮也要同步不选中
					document.getElementById("checkedAllBox").checked = false;
				}
				
				//3.#checkedRevBtn
				document.getElementById("checkedRevBtn").onclick = function(){
					var items = document.getElementsByName("items");
					var flag = true;
					for(var i=0;i<items.length;i++){
						items[i].checked = !items[i].checked;
						if(!items[i].checked){
							flag = false;
						}
					}
					// 全选按钮也要同步选中或不选中
					document.getElementById("checkedAllBox").checked = flag;
				}
				
				//4.#sendBtn
				document.getElementById("sendBtn").onclick = function(){
					var items = document.getElementsByName("items");
					var arr = [];
					for(var i=0;i<items.length;i++){
						if(items[i].checked){
							arr.push(items[i].value);
						}
					}
					alert(arr);
				}
				
				//5.#checkedAllBox
				document.getElementById("checkedAllBox").onclick = function(){
					var items = document.getElementsByName("items");
					for(var i=0;i<items.length;i++){
						// 在事件的响应函数中，响应函数是给谁绑定的this就是谁
						items[i].checked = this.checked; 
					}
				}
				
				//6.items
				var flag;
				var items = document.getElementsByName("items");
				for(var i=0;i<items.length;i++){
					items[i].onclick = function(){
						flag = true;
						for(var j=0;j<items.length;j++){
							if(!items[j].checked){
								flag = false;
								break;
							}
						}
						document.getElementById("checkedAllBox").checked = flag;
					}
				}

			};
		</script>
	</head>
	<body>
		<form method="post" action="">
			你爱好的运动是？<input type="checkbox" id="checkedAllBox" />全选/全不选 
			
			<br />
			<input type="checkbox" name="items" value="足球" />足球
			<input type="checkbox" name="items" value="篮球" />篮球
			<input type="checkbox" name="items" value="羽毛球" />羽毛球
			<input type="checkbox" name="items" value="乒乓球" />乒乓球
			<br />
			<input type="button" id="checkedAllBtn" value="全　选" />
			<input type="button" id="checkedNoBtn" value="全不选" />
			<input type="button" id="checkedRevBtn" value="反　选" />
			<input type="button" id="sendBtn" value="提　交" />
		</form>
	</body>
</html>
